package com.example.travel.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis分布式锁工具类
 * 用于防止并发下单时的脏读/写问题
 */
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 尝试获取分布式锁
     * @param key 锁的键
     * @param value 锁的值（用于标识锁的拥有者）
     * @param expireTime 锁的过期时间（秒）
     * @return 是否成功获取锁
     */
    public boolean tryLock(String key, String value, long expireTime) {
        try {
            Boolean result = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
            return result != null && result;
        } catch (Exception e) {
            System.out.println("获取Redis锁失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 释放分布式锁
     * @param key 锁的键
     * @param value 锁的值（用于验证锁的拥有者）
     * @return 是否成功释放锁
     */
    public boolean releaseLock(String key, String value) {
        try {
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                           "return redis.call('del', KEYS[1]) " +
                           "else return 0 end";
            Long result = redisTemplate.execute(
                new org.springframework.data.redis.core.script.DefaultRedisScript<>(script, Long.class),
                java.util.Collections.singletonList(key),
                value
            );
            return result != null && result > 0;
        } catch (Exception e) {
            System.out.println("释放Redis锁失败: " + e.getMessage());
            return false;
        }
    }
}

